/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iodegree;

import iodegree.dataStrucure.BatchRatio;
import iodegree.lib.MyTableModel;
import iodegree.lib.CommonsLib;
import iodegree.lib.D;
import iodegree.lib.database.DBHandle;
import java.io.File;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;

/**
 *
 * @author Libra
 */
public class DistStatsUI extends javax.swing.JFrame {

    /**
     * Creates new form DistStatsUI
     */
    public DistStatsUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        DataFileChooser = new javax.swing.JFileChooser();
        gluGABAGroup = new javax.swing.ButtonGroup();
        btnOpenDbDefault = new javax.swing.JButton();
        btnOpenDatabase = new javax.swing.JButton();
        lblOpenDatabase = new javax.swing.JLabel();
        lblQueryOption = new javax.swing.JLabel();
        btnQuery = new javax.swing.JButton();
        mainScrollPane = new javax.swing.JScrollPane();
        resultTable = new javax.swing.JTable();
        rdoGABAOnGlu = new javax.swing.JRadioButton();
        rdoGABAOnGABA = new javax.swing.JRadioButton();
        rdoGluOnGlu = new javax.swing.JRadioButton();
        rdoGluOnGABA = new javax.swing.JRadioButton();
        binsScrollPane = new javax.swing.JScrollPane();
        txtBins = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        statsScrollPane = new javax.swing.JScrollPane();
        statsTable = new javax.swing.JTable();
        chkSepPost = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnOpenDbDefault.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnOpenDbDefault.setText("Default");
        btnOpenDbDefault.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenDbDefaultActionPerformed(evt);
            }
        });

        btnOpenDatabase.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnOpenDatabase.setText("Open");
        btnOpenDatabase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenDatabaseActionPerformed(evt);
            }
        });

        lblOpenDatabase.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblOpenDatabase.setText("1. Open Database File :");

        lblQueryOption.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblQueryOption.setText("2. Query Option:");

        btnQuery.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnQuery.setText("Query");
        btnQuery.setEnabled(false);
        btnQuery.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQueryActionPerformed(evt);
            }
        });

        mainScrollPane.setViewportView(resultTable);

        mainScrollPane.setColumnHeaderView(null);

        gluGABAGroup.add(rdoGABAOnGlu);
        rdoGABAOnGlu.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        rdoGABAOnGlu.setText("GABA On Glu");
        rdoGABAOnGlu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoGABAOnGluActionPerformed(evt);
            }
        });

        gluGABAGroup.add(rdoGABAOnGABA);
        rdoGABAOnGABA.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        rdoGABAOnGABA.setText("GABA On GABA");
        rdoGABAOnGABA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoGABAOnGABAActionPerformed(evt);
            }
        });

        gluGABAGroup.add(rdoGluOnGlu);
        rdoGluOnGlu.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        rdoGluOnGlu.setSelected(true);
        rdoGluOnGlu.setText("Glu On Glu");
        rdoGluOnGlu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoGluOnGluActionPerformed(evt);
            }
        });

        gluGABAGroup.add(rdoGluOnGABA);
        rdoGluOnGABA.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        rdoGluOnGABA.setText("Glu On GABA");
        rdoGluOnGABA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoGluOnGABAActionPerformed(evt);
            }
        });

        txtBins.setColumns(5);
        txtBins.setRows(5);
        txtBins.setText("50\n100\n150\n200\n250\n350\n550");
        binsScrollPane.setViewportView(txtBins);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Bins");

        statsScrollPane.setViewportView(statsTable);

        statsScrollPane.setColumnHeaderView(null);

        chkSepPost.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        chkSepPost.setSelected(true);
        chkSepPost.setText("Seperate Post Type");
        chkSepPost.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkSepPostActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblOpenDatabase)
                            .addComponent(lblQueryOption))
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnOpenDatabase)
                                .addGap(18, 18, 18)
                                .addComponent(btnOpenDbDefault)
                                .addGap(0, 480, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(rdoGluOnGlu)
                                .addGap(18, 18, 18)
                                .addComponent(rdoGluOnGABA)
                                .addGap(18, 18, 18)
                                .addComponent(rdoGABAOnGlu)
                                .addGap(18, 18, 18)
                                .addComponent(rdoGABAOnGABA)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(chkSepPost))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(34, 34, 34))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(binsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(mainScrollPane, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(statsScrollPane)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnQuery)
                                .addGap(0, 693, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addComponent(lblQueryOption))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblOpenDatabase)
                            .addComponent(btnOpenDatabase)
                            .addComponent(btnOpenDbDefault))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(rdoGluOnGlu)
                            .addComponent(rdoGABAOnGlu)
                            .addComponent(rdoGABAOnGABA)
                            .addComponent(rdoGluOnGABA)
                            .addComponent(chkSepPost))))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnQuery)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(binsScrollPane)
                    .addComponent(mainScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(statsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOpenDbDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenDbDefaultActionPerformed
        pathToFile = CommonsLib.getDefaultFile();
        btnQuery.setEnabled(true);
    }//GEN-LAST:event_btnOpenDbDefaultActionPerformed
    
    private void btnOpenDatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenDatabaseActionPerformed
        int returnVal = DataFileChooser.showOpenDialog(this);
        if (returnVal == DataFileChooser.APPROVE_OPTION) {
            pathToFile = DataFileChooser.getSelectedFile().getAbsolutePath();
//            System.out.println("File " + pathToFile + " opened.");
            btnQuery.setEnabled(true);
        }
    }//GEN-LAST:event_btnOpenDatabaseActionPerformed
    
    private void btnQueryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQueryActionPerformed

        /*
         * get slot list and con list with dist
         */
        DBHandle db = new DBHandle();
        BatchRatio ratioes = new BatchRatio();
        ratioes.setBins(getBins());
        db.ratioBatches(pathToFile, boolSepPost, fwGlu, revGlu, "Dist", ratioes);
//        D.p(Arrays.deepToString(ratioes.getBatchRatio()));
        Object[][] ratioTabD;
        ratioTabD = new Object[ratioes.getBatches().size() + 1][ratioes.getBins().size() + 1];
        ratioes.genBatchRatio();
        for (int i = 1; i < ratioTabD.length; i++) {
            ratioTabD[i][0] = ratioes.getBatches().get(i - 1);
            System.arraycopy(ratioes.getBatchRatio()[i - 1], 0, ratioTabD[i], 1, ratioes.getBins().size());
        }
        
        for (int i = 1; i < ratioTabD[0].length; i++) {
            ratioTabD[0][i] = "Up to " + Integer.toString(ratioes.getBins().get(i - 1));
        }
        
        MyTableModel mainTableModel = new MyTableModel(ratioTabD);
        mainScrollPane.setColumnHeaderView(null);
        resultTable.setModel(mainTableModel);

        /*
         * Fill statistics table
         */
        Object[][] statsTabD = new Object[3][ratioes.getBins().size() + 1];
        for (int i = 0; i < ratioes.getBins().size(); i++) {
            SummaryStatistics stats = new SummaryStatistics();
            for (int j = 0; j < ratioes.getBatches().size(); j++) {
                if (ratioes.getBatchRatio()[j][i] == null) {
//                    System.out.println("null!");
                } else {
                    stats.addValue(ratioes.getBatchRatio()[j][i]);
                }
            }
            statsTabD[0][i + 1] = new Double(stats.getMean());
            statsTabD[1][i + 1] = new Double(stats.getStandardDeviation());
            statsTabD[2][i + 1] = new Double(
                    stats.getStandardDeviation() / Math.sqrt(stats.getN()));
        }
        statsTabD[0][0] = "Mean";
        statsTabD[1][0] = "S.D.";
        statsTabD[2][0] = "S.E.M.";
        
        MyTableModel statsTableModel = new MyTableModel(statsTabD);
        statsScrollPane.setColumnHeaderView(null);
        statsTable.setModel(statsTableModel);
        
    }//GEN-LAST:event_btnQueryActionPerformed
    
    private void rdoGABAOnGluActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoGABAOnGluActionPerformed
        fwGlu = false;
        revGlu = true;
    }//GEN-LAST:event_rdoGABAOnGluActionPerformed
    
    private void rdoGABAOnGABAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoGABAOnGABAActionPerformed
        fwGlu = false;
        revGlu = false;
//        gluTransfer = false;
//        txtBinSize.setText("12");
    }//GEN-LAST:event_rdoGABAOnGABAActionPerformed
    
    private void rdoGluOnGluActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoGluOnGluActionPerformed
        fwGlu = true;
        revGlu = true;
//        gluTransfer = true;
//        txtBinSize.setText("23");
    }//GEN-LAST:event_rdoGluOnGluActionPerformed
    
    private void rdoGluOnGABAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoGluOnGABAActionPerformed
        fwGlu = true;
        revGlu = false;
    }//GEN-LAST:event_rdoGluOnGABAActionPerformed
    
    private void chkSepPostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkSepPostActionPerformed
        if (chkSepPost.isSelected()) {
            boolSepPost = true;
            rdoGluOnGlu.setText("Glu On Glu");
            rdoGABAOnGlu.setText("GABA On Glu");
            rdoGluOnGABA.setVisible(true);
            rdoGABAOnGABA.setVisible(true);
            
        } else {
            boolSepPost = false;
            rdoGluOnGlu.setText("Glu");
            rdoGABAOnGlu.setText("GABA");
            rdoGluOnGABA.setVisible(false);
            rdoGABAOnGABA.setVisible(false);
        }
    }//GEN-LAST:event_chkSepPostActionPerformed
    
    private ArrayList<Integer> getBins() {
        ArrayList<Integer> bin = new ArrayList<>(10);
        StringTokenizer st = new StringTokenizer(txtBins.getText());
        while (st.hasMoreTokens()) {
            bin.add(Integer.parseInt(st.nextToken()));
        }
        return bin;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DistStatsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DistStatsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DistStatsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DistStatsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DistStatsUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser DataFileChooser;
    private javax.swing.JScrollPane binsScrollPane;
    private javax.swing.JButton btnOpenDatabase;
    private javax.swing.JButton btnOpenDbDefault;
    private javax.swing.JButton btnQuery;
    private javax.swing.JCheckBox chkSepPost;
    private javax.swing.ButtonGroup gluGABAGroup;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel lblOpenDatabase;
    private javax.swing.JLabel lblQueryOption;
    private javax.swing.JScrollPane mainScrollPane;
    private javax.swing.JRadioButton rdoGABAOnGABA;
    private javax.swing.JRadioButton rdoGABAOnGlu;
    private javax.swing.JRadioButton rdoGluOnGABA;
    private javax.swing.JRadioButton rdoGluOnGlu;
    private javax.swing.JTable resultTable;
    private javax.swing.JScrollPane statsScrollPane;
    private javax.swing.JTable statsTable;
    private javax.swing.JTextArea txtBins;
    // End of variables declaration//GEN-END:variables
    private String pathToFile;
    private boolean fwGlu = true;
    private boolean revGlu = true;
//    private BatchRatio ratioes;
//    private ArrayList<BatchNInterest> lstConn;
//    private ArrayList<Integer> distBin;
//    private Object[][] mainTableData;
//    private Object[][] statsTableData;
    private boolean boolSepPost = true;
}
